package com.ujiuye.web;

import com.ujiuye.enity.User;
import com.ujiuye.service.UserService;
import org.apache.commons.beanutils.BeanUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

@WebServlet("/login")
public class Login extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取响应输出流(字符输出流-->向页面输出文本信息)
        PrintWriter pw = resp.getWriter();
        //获取页面数据  用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("pwd");
        //获取记住密码选项
        String save = req.getParameter("save");
        UserService us = new UserService();
        User u = us.login(username, password);
        if (u != null) {
            //登录成功-->判断是否勾选了记住密码选项
            if ("checkOn".equals(save)) {
                //勾选,创建cookie保存账号和密码
                Cookie c1 = new Cookie("username", u.getUsername());
                Cookie c2 = new Cookie("pwd", u.getPwd());
                //设置存活时间并添加到浏览器
                c1.setMaxAge(60 * 60 * 24 * 7);
                c2.setMaxAge(60 * 60 * 24 * 7);
                resp.addCookie(c1);
                resp.addCookie(c2);
            }
            //将用户信息保存到session里
            HttpSession session = req.getSession();
            session.setAttribute("u", u);
            req.getRequestDispatcher("/show").forward(req, resp);
        } else {
            pw.println("用户名或者密码错误,请重新<a href='login.jsp'>登录</a>");
        }

    }
}
